<template>
  <div class="container">
    <div class="app-container">
      <el-card>
        <div class="left">
          <el-input v-model="queryParams.keyword" style="margin-bottom: 10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="searchResult" />
          <!-- 树形组件 -->
          <!-- node-key 指定对象里面的某一个属性 -->
          <!-- 例如我指定的是 id，调用这个方法 setCurrentKey 的时候传递了 id 就可以高亮 -->
          <el-tree ref="deptsRef" node-key="id" :data="depts" :props="{ label: 'name' }" default-expand-all :expand-on-click-node="false" highlight-current @current-change="selectNode" />
        </div>
        <div class="right">
          <el-row class="opeate-tools" type="flex" justify="end">
            {{ age }}
            <!-- <el-button size="mini" type="primary" :disabled="!checkPermission2(ADD_EMPLOYEE)" @click="$router.push('/employee/detail')">添加员工</el-button> -->
            <el-button v-checkPermission="ADD_EMPLOYEE" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
            <el-button size="mini" @click="showDialog = true">excel导入</el-button>
            <el-button size="mini" @click="exportExcel">excel导出</el-button>
          </el-row>
          <!-- 表格组件 -->
          <el-table :data="list">
            <el-table-column align="center" label="头像" prop="staffPhoto">
              <template #default="{row}">
                <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" />
                <div v-else class="username">{{ row.username?.charAt(0) }}</div>
              </template>
            </el-table-column>
            <el-table-column label="姓名" prop="username" />
            <el-table-column label="手机号" sortable prop="mobile" />
            <el-table-column label="工号" sortable prop="workNumber" />
            <el-table-column label="聘用形式">
              <template #default="{ row }">
                <el-tag v-if="row.formOfEmployment === 1">正式</el-tag>
                <el-tag v-else-if="row.formOfEmployment === 2">非正式</el-tag>
                <el-tag v-else>未知</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="部门" prop="departmentName" />
            <el-table-column label="入职时间" sortable prop="timeOfEntry" />
            <el-table-column label="操作" width="280px">
              <template #default="scope">
                <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${scope.row.id}`)">查看</el-button>
                <el-button size="mini" type="text" @click="showRoleDialogFn(scope.row.id)">角色</el-button>
                <!-- <el-button size="mini" type="text" @click="delEmployee(scope.row.id)">删除</el-button> -->
                &nbsp;
                <el-popconfirm
                  title="这是一段内容确定删除吗？"
                  @confirm="delEmployee(scope.row.id)"
                >
                  <template #reference>
                    <el-button v-checkPermission="DEL_EMPLOYEE" size="mini" type="text">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-row style="height: 60px" align="middle" type="flex" justify="center">
            <el-pagination layout="total,prev, pager, next" :total="total" :page-size="queryParams.pagesize" :current-page="queryParams.page" @current-change="changePage" />
          </el-row>
        </div>
      </el-card>
      <import-excel :show-excel-dialog.sync="showDialog" @getDepartments="getDepartments" />
      <el-dialog :visible.sync="showRoleDialog" title="分配角色">
        <!-- v-model 双向绑定数据，收集数据的 -->
        <!-- //!v-model 收集到的是 el-checkbox 的 label 属性，可以用默认插槽来展示文字 -->
        <el-checkbox-group v-model="roleIds">
          <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
        </el-checkbox-group>
        <template #footer>
          <el-row type="flex" justify="center">
            <el-button @click="addRole">确定</el-button>
            <el-button @click="showRoleDialog = false">取消</el-button>
          </el-row>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { assignRole, delEmployee, exportEmployee, getEmployeeDetail, getEmployeeList, getEnableRoleList } from '@/api/employee'
import { getDepartments } from '@/api/departments'
import { transListToTreeData } from '@/utils'
import { saveAs } from 'file-saver'
import ImportExcel from './components/import-excel.vue'
import { ADD_EMPLOYEE, DEL_EMPLOYEE } from '@/constants'
import mixin from '@/mixins'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  mixins: [mixin],
  data() {
    return {
      DEL_EMPLOYEE,
      age: 19,
      ADD_EMPLOYEE,
      showRoleDialog: false, // 控制角色弹框
      roleList: [], // 角色列表
      roleIds: [], // 收集到的角色 ID
      currentUserId: null,
      showDialog: false,
      depts: [],
      queryParams: {
        // 选中的组织架构的 ID
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      list: [],
      total: 0,
      bBar: true
    }
  },
  created() {
    console.log(2)
    this.getDepartments()
  },
  methods: {
    async showRoleDialogFn(userId) {
      this.currentUserId = userId
      // 获取所有角色
      this.roleList = await getEnableRoleList()
      // 获取当前用户的角色
      const { roleIds } = await getEmployeeDetail(userId)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    async addRole() {
      // 根据用户 id 和 当前选中的数据分角色
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    },
    async exportExcel() {
      saveAs(await exportEmployee(), '员工信息.xlsx')
    },
    async getDepartments() {
      // !数据变化到视图更新这个过程是异步的，如果直接执行选中操作 setCurrentKey 是不行的（因为视图可能还没渲染完呢）
      this.depts = transListToTreeData(await getDepartments(), 0)
      // !默认应该是第 0 项的 id
      this.queryParams.departmentId = this.depts[0].id
      // 高亮 ID 对应的这一项
      this.$nextTick(() => {
        this.$refs.deptsRef.setCurrentKey(this.queryParams.departmentId)
      })
      // !# 注意调用的位置
      this.getEmployeeList()
    },
    selectNode(node) {
      this.queryParams.departmentId = node.id
      // 每次从第一页开始要数据
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    changePage(page) {
      // 改变查询条件之后，重新发请求
      this.queryParams.page = page
      this.getEmployeeList()
    },
    searchResult() {
      // 没必要把 timer 写到 data 里面，因为不需要再页面展示
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        // 每次从第一页开始要数据
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 500)
      /* if (this.bBar) {
        this.bBar = false
        setTimeout(() => {
          this.queryParams.page = 1
          this.getEmployeeList()
          this.bBar = true
        }, 500)
      } */
    },
    async delEmployee(id) {
      await delEmployee(id)
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.getEmployeeList()
    }
  }
}
</script>

<style lang="scss" scoped>
    .app-container {
        :deep(.el-card__body) {
            background: #fff;
            display: flex;
        }

        .left {
            width: 280px;
            padding: 20px;
            border-right: 1px solid #eaeef4;
        }

        .right {
            flex: 1;
            padding: 20px;

            .opeate-tools {
                margin: 10px;
            }

            .username {
                height: 30px;
                width: 30px;
                line-height: 30px;
                text-align: center;
                border-radius: 50%;
                color: #fff;
                background: #04c9be;
                font-size: 12px;
                display: inline-block;
            }
        }
    }
</style>
